// pages/address-edit/address-edit.js
var api = require('../../api.js');
var commonCityData = require('../../utils/city.js')


var addressParse = require('../../utils/parseArea/address-parse.js');
var area_picker = require('../../area-picker/area-picker.js');
var app = getApp();
Page({
  data: {
    copyinput: "",
    name: "",
    mobile: "",
    detail: "",
    district: null,
    shiti: null,
    provinces: [],
    citys: [],
    defaultProvinceCode: 2,
    defaultCityCode: 3,
    defaultCountyCode: 16,
    defaultAddressCode: '057750',
    districts: [],
    selProvince: '请选择',
    selCity: '请选择',
    selDistrict: '请选择',
    selProvinceIndex: 0,
    selCityIndex: 0,
    selDistrictIndex: 0
  },
  initCityData: function(level, obj) {
    if (level == 1) {
      var pinkArray = [];
      for (var i = 0; i < commonCityData.cityData.length; i++) {
        pinkArray.push(commonCityData.cityData[i].name);
      }
      this.setData({
        provinces: pinkArray
      });
    } else if (level == 2) {
      var pinkArray = [];
      var dataArray = obj.cityList
      for (var i = 0; i < dataArray.length; i++) {
        pinkArray.push(dataArray[i].name);
      }
      this.setData({
        citys: pinkArray
      });
    } else if (level == 3) {
      var pinkArray = [];
      var dataArray = obj.districtList
      for (var i = 0; i < dataArray.length; i++) {
        pinkArray.push(dataArray[i].name);
      }
      this.setData({
        districts: pinkArray
      });
    }

  },
  bindPickerProvinceChange: function(event) {
    var selIterm = commonCityData.cityData[event.detail.value];
    this.setData({
      selProvince: selIterm.name,
      selProvinceIndex: event.detail.value,
      selCity: '请选择',
      selCityIndex: 0,
      selDistrict: '请选择',
      selDistrictIndex: 0
    })
    this.initCityData(2, selIterm)
  },
  bindPickerCityChange: function(event) {
    var selIterm = commonCityData.cityData[this.data.selProvinceIndex].cityList[event.detail.value];
    this.setData({
      selCity: selIterm.name,
      selCityIndex: event.detail.value,
      selDistrict: '请选择',
      selDistrictIndex: 0
    })
    this.initCityData(3, selIterm)
  },
  bindPickerChange: function(event) {
    var selIterm = commonCityData.cityData[this.data.selProvinceIndex].cityList[this.data.selCityIndex].districtList[event.detail.value];
    if (selIterm && selIterm.name && event.detail.value) {
      this.setData({
        selDistrict: selIterm.name,
        selDistrictIndex: event.detail.value
      })
    }
  },

  bindRegionChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    console.log('picker:', e.detail.code);
    console.log('picker-postcode:', e.detail.postcode);
    console.log(e.detail.value[0], e.detail.value[1], e.detail.value[2]);
    this.setData({
      selProvince: e.detail.value[0],
      selCity: e.detail.value[1],
      selDistrict: e.detail.value[2],
    });

  },

  onLoad: function(options) {
    var page = this;
    this.initCityData(1);

    // page.getDistrictData(function (data) {
    //     area_picker.init({
    //         page: page,
    //         data: data,
    //     });
    // });

    // console.log(addressParse.parse("姓名：杨玉地址：广东深圳市龙岗区横岗街道 六约社区 深竹路工业园2号 B栋办公楼1层 2办公室"));

    page.setData({
      address_id: options.id,
    });
    if (options.id) {
      wx.showLoading({
        title: "正在加载",
        mask: true,
      });
      app.request({
        url: api.user.address_detail,
        data: {
          id: options.id,
        },
        success: function(res) {
          console.log(res)
          wx.hideLoading();
          if (res.code == 200) {
            page.setData(res.data);
            page.setData({
              selCity: res.data.city,
              selProvince: res.data.province,
              selDistrict: res.data.region,

            })
          }
        }
      });
    }
  },

  getDistrictData: function(cb) {
    var district = wx.getStorageSync("district");
    if (!district) {
      wx.showLoading({
        title: "正在加载",
        mask: true,
      });
      app.request({
        url: api.default.district,
        success: function(res) {
          wx.hideLoading();
          if (res.code == 200) {
            district = res.data;
            wx.setStorageSync("district", district);
            cb(district);
          }
        }
      });
      return;
    }
    cb(district);
  },

  onAreaPickerConfirm: function(e) {
    //console.log(e);
    var page = this;
    page.setData({
      district: {
        province: {
          id: e[0].id,
          name: e[0].name,
        },
        city: {
          id: e[1].id,
          name: e[1].name,
        },
        district: {
          id: e[2].id,
          name: e[2].name,
        },
      }
    });
  },

  chang: function() {
    this.data.shiti = addressParse.parse(this.data.copyinput)
    console.log(this.data.shiti)
    this.setData({
      name: this.data.shiti.name,
      phoneNumber: this.data.shiti.mobile,
      detailAddress: this.data.shiti.addr,
      selProvince: this.data.shiti.province,
      selCity: this.data.shiti.city,
      selDistrict: this.data.shiti.area
    })
  },

  saveAddress: function() {
    var page = this;
    var myreg = /^([0-9]{6,12})$/;
    var myreg2 = /^(\d{3,4}-\d{6,9})$/;
    console.log(myreg2.test(page.data.mobile));
    if (!myreg.test(page.data.phoneNumber) && !myreg2.test(page.data.phoneNumber)) {
      wx.showToast({
        title: "联系电话格式不正确",
        image: "/images/icon-warning.png",
      });
      return false;
    }
    wx.showLoading({
      title: "正在保存",
      mask: true,
    });
    var district = page.data.district;
    console.log("district")
    console.log(district)

    if (!district) {
      district = {
        province: {
          id: ""
        },
        city: {
          id: ""
        },
        district: {
          id: ""
        }
      };
    }
    app.request({
      url: api.user.address_save,
      data: {
        id: page.data.address_id || "",
        name: page.data.name,
        phoneNumber: page.data.phoneNumber,
        province: page.data.selProvince,
        city: page.data.selCity,
        region: page.data.selDistrict,
        detailAddress: page.data.detailAddress,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code == 200) {
          wx.navigateBack();
        }
        if (res.code == 1) {
          wx.showToast({
            title: res.msg,
            image: "/images/icon-warning.png",
          });
        }
      }
    });
  },

  inputDetailAddresChange: function(e) {
    var value = e.detail.value;
    this.setData({
      copyinput: value
    });
  },

  inputBlur: function(e) {
    //console.log(JSON.stringify(e));
    var name = e.currentTarget.dataset.name;
    var value = e.detail.value;
    //var data = '{"form":{"' + name + '":"' + value + '"}}';
    var data = '{"' + name + '":"' + value + '"}';
    this.setData(JSON.parse(data));
  },

  getWechatAddress: function(e) {
    var page = this;
    wx.chooseAddress({
      success: function(e) {
        if (e.errMsg != 'chooseAddress:ok')
          return;
        wx.showLoading();
        app.request({
          url: api.user.wechat_district,
          data: {
            national_code: e.nationalCode,
          },
          success: function(res) {
            if (res.code == 1) {
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
              });
            }
            page.setData({
              name: e.userName || "",
              mobile: e.telNumber || "",
              detail: e.detailInfo || "",
              district: res.data.district,
            });
          },
          complete: function() {
            wx.hideLoading();
          }
        });
      }
    });
  },

  onReady: function() {

  },
  onShow: function() {

  },
});